import React from 'react';

import router from '../../../utils/routerDecorator';
import {get, post, put, apiDelete} from '../../../logic/api';
import PageList from '../../components/PageList';

import { Popconfirm, Button } from 'antd';

import { observable, toJS } from 'mobx';
import { observer } from 'mobx-react';

import styles from './main.less';
import { showModal } from "../../components/showModal";

import { Input, InputNumber } from '../../components/MobxForm';

class Edit extends React.Component {
  onConfirm = async () => {
    const { target, onConfirm, dismiss } = this.props;
    onConfirm && await onConfirm(target);
    dismiss();
  };

  render() {
    const { target, title, dismiss } = this.props;
    return (
      <div className={styles.edit}>
        <h2>{title}</h2>
        <Input target={target} field="name" label="描述" />
        <InputNumber target={target} field="oprice" label="原价" min={0} step={0.01}/>
        <InputNumber target={target} field="nprice" label="现价" min={0} step={0.01}/>
        <InputNumber target={target} field="stock" label="库存"  min={0}/>
        <div className="ant-modal-footer">
          <Button onClick={dismiss}>取消</Button>
          <Button type="primary" onClick={this.onConfirm}>确定</Button>
        </div>
      </div>
    );
  }
}

@router('/site/products')
@observer
export default class List extends React.Component {
  @observable
  goodInfo = null;

  async componentDidMount(){
    const {location:{query:{goodId}}} = this.props;
    const { data } = await get(`/admin/goods/goodsinfo/${goodId}`);
    this.goodInfo = data;
  }

  fetchData = async () => {
    const {location:{query:{goodId}}} = this.props;
    const {ok, content} = await get(`/admin/goods/${goodId}/products`);
    if (!ok) { throw new Error('获取失败');}
    return {
      content,
      count: content.length,
    };
  }

  deleteItem = async (record) => {
    await apiDelete(`/admin/goods/products/${record.id}`);
    const { list } = this.refs;
    if (list) {
      await list.fetchData();
    }
  }

  addItem = async (record) =>{
    try {
      const {location:{query:{goodId}}} = this.props;
      await post(`/admin/goods/${goodId}/products/create`, toJS(record));
      const {list} = this.refs;
      if (list) {
        await list.fetchData();
      }
    } catch (err) {
      alert('设置失败。请重试。');
    }
  };

  editItem = async (record) => {
    try {
      const {id, ...others} = toJS(record);
      await put(`/admin/goods/products/${id}`, others);
      const {list} = this.refs;
      if (list) {
        await list.fetchData();
      }
    } catch (err) {
      alert('保存失败。请重试。');
      throw err;
    }
  };

  columns = [
    { title: 'ID', dataIndex: 'id'},
    { title: '描述', dataIndex:'name'},
    { title: '原价', dataIndex:'oprice'},
    { title: '现价', dataIndex:'nprice'},
    { title: '库存', dataIndex:'stock'},
    {
      title: (
        <div>
          <Button type="primary" onClick={()=>{
            showModal(<Edit
              title="新建"
              target={
                observable({
                  name: null,
                  oprice: this.goodInfo.oprice,
                  nprice: this.goodInfo.nprice,
                  stock: 0,
                })
              }
              onConfirm={this.addItem}
            />);
          }}>新建</Button>
        </div>
      ),
      width:'25%',
      render: (text, record)=>(
        <div className = {styles.operations}>
          <Button type = "primary" onClick={() => {
            showModal(<Edit
              title="编辑"
              target={observable(record)}
              onConfirm={this.editItem}
            />);
          }}>
            编辑
          </Button>
          <Popconfirm title = "确定删除？" onConfirm={() => this.deleteItem(record)}>
            <Button type = "ghost">
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  render(){
    if (!this.goodInfo) {
      return null;
    }
    return (
      <div>
        <div>
          商品： {this.goodInfo.cname}({this.goodInfo.ename}),
          原价： {this.goodInfo.oprice},
          现价： {this.goodInfo.nprice},
        </div>
        <PageList
          ref="list"
          columns = {this.columns}
          fetchData = {this.fetchData}
        />
      </div>
    );
  }
}
